package org.jeecg.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.w3c.dom.Document;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.swing.Java2DRenderer;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2023/11/6 15:17
 */
public class FreemarkerUtil {
    private static Configuration config = null;

    /**
     * 初始化获取html模板
     */
    static {
        config = new Configuration(Configuration.VERSION_2_3_20);
        config.setDefaultEncoding("UTF-8");
        try {
            config.setClassForTemplateLoading(FreemarkerUtil.class, "/ftl");
        } catch (Exception e) {
            e.printStackTrace();
//            log.error(e.toString());
        }
    }

    /**
     * 把BufferedImage 图片转base64
     *
     * @param bufferedImage
     * @return
     * @throws Exception
     */
   private static String bufferedImageToBase64(BufferedImage bufferedImage) throws Exception {
       String png_base64;//转换成base64串
       //io流
       try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
           ImageIO.write(bufferedImage, "jpg", baos);//写入流中
           byte[] bytes = baos.toByteArray();//转换成字节
           png_base64 = Base64.getEncoder().encodeToString(bytes);
           png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
       }
       return "data:image/jpg;base64," + png_base64;
   }

    /**
     * 将html转成base64字节
     *
     * @param html
     * @param width
     * @param height
     * @param imgName 图片位置加名称
     * @return
     * @throws Exception
     */
    public static String html2ImgBase64(String html, int width, int height,String imgName,String imgPath) throws Exception {
        byte[] bytes = html.getBytes();
        BufferedImage img;
        try (ByteArrayInputStream bin = new ByteArrayInputStream(bytes)) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(bin);
            Java2DRenderer renderer = new Java2DRenderer(document, width, height);
            SharedContext sharedContext = renderer.getSharedContext();
            sharedContext.setDotsPerPixel(3);
            sharedContext.setDPI(523);
            img = renderer.getImage();
            if(imgName!=null && imgName.contains(".jpg")){
                FileOutputStream fileOutputStream = new FileOutputStream(imgPath + File.separator + imgName);
                ImageIO.write(img, "jpg", fileOutputStream);
                fileOutputStream.close();
                bin.close();
                return imgName;
            }
        }
//       return bufferedImageToBase64(img);
         return imgName;
    }

    public static String html2ImgBase64Old(String html, int width, int height,String imgName,String imgPath) throws Exception {
        byte[] bytes = html.getBytes();
        BufferedImage img;
        try (ByteArrayInputStream bin = new ByteArrayInputStream(bytes)) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(bin);
            Java2DRenderer renderer = new Java2DRenderer(document, width, height);
            SharedContext sharedContext = renderer.getSharedContext();
            sharedContext.setDotsPerPixel(3);
            sharedContext.setDPI(523);
            img = renderer.getImage();
        }
      return bufferedImageToBase64(img);
    }
    /**
     * 获取模板数据
     *
     * @param template
     * @param params
     * @return
     * @throws Exception
     */
    public static String generate(String template, Map params) throws Exception {
        Template tp = config.getTemplate(template);
        tp.setEncoding("UTF-8");
        StringWriter stringWriter = new StringWriter();
        String htmlStr;
        try {
            tp.process(params, stringWriter);
            htmlStr = stringWriter.toString();
            stringWriter.flush();
        } finally {
            stringWriter.close();
        }
        return htmlStr;
    }
}
